# This Python file uses the following encoding: utf-8
import re
import sys
import time
import datetime
import logging
import  json
from elasticsearch import Elasticsearch
# 10.15.212.31  online
es = Elasticsearch(hosts='10.15.226.153')

# print(es.delete(index="index_id_chapter_1446710513161_20151105160153170", doc_type="chapter", id=3219914))


# es find
index_name="_all";
index_type="chapter"
# esRet=es.get(index=index_name, doc_type=index_type, id=7505661)['_source']
# print(json.dumps(esRet))

# filter 查询 不计算相关性 可缓存
dslfilter={
    'filter':{
        "bool": {
            "must": [
                # {
                #     "terms": {
                #         "title": [
                #             "【一】",
                #             "标题"
                #         ]
                #     }
                # },
                {
                    "range": {
                        "auditUpdateTime": {
                            "ge": "2016-07-27 18:33:30",
                            # "le":"2016-07-27 14:00:00"
                        }
                    }
                }
            ]
        }
    }
}
# filter+query 查询 结构：{query:{filtered：{}}}  好处：借助于filter的速度可以快速过滤出文档，然后再由query根据条件来匹配。
dslfilterQuery={
    "query": {
        "filtered": {
            "query": {
                "match": {
                    "title": "第2章"
                }
            },
            "filter": {
                "term": {
                    "title": "第2章"
                }
            }
        }
    }
}
# query 会根据近义词，相似性等给出相关性分数，并按相关性排序， 适合全文搜索这种本身没有准确答案的领域
dslQuery={
    "query": {
        "bool": {
            "must": [
                {
                    "terms": {
                        "title": [
                            "【一】",
                            "标题"
                        ]
                    }
                },
                {
                    "range": {
                        "createTime": {
                            "gt": "2016-07-26 18:33:29"
                        }
                    }
                }
            ]
        }
    }
}
esRet=es.search(
    index=index_name,
    doc_type='cartoonbook',
    body=dslfilter,
    from_=0,
    size=1,
    # explain=1,
    # fields=['title','createTime']
)
print(json.dumps(esRet,indent=4))